package com.example.socket;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @Classname ServletResponse
 * @Description TODO
 * @Date 2023/4/27 11:08
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class ServletResponse {

    private OutputStream outputStream;

    public ServletResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public OutputStream getOutputStream(){
        return this.outputStream;
    }

    public void wirte(String content){
        try {
            JSONObject obj=new JSONObject();
            obj.put("code",1);
            obj.put("msg",content);
            byte[] responseBytes = obj.toJSONString().getBytes("UTF-8");
            OutputStream outputStream = this.outputStream;
            outputStream.write("HTTP/1.1 200 OK\r\n".getBytes("UTF-8"));
            outputStream.write("Content-Type: application/json\r\n".getBytes("UTF-8"));
            outputStream.write(("Content-Length: " + responseBytes.length + "\r\n").getBytes("UTF-8"));
            outputStream.write("\r\n".getBytes("UTF-8"));
            outputStream.write(responseBytes);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void wirteError(String content){
        try {
            JSONObject obj=new JSONObject();
            obj.put("code",1);
            obj.put("msg",content);
            byte[] responseBytes = obj.toJSONString().getBytes("UTF-8");
            OutputStream outputStream = this.outputStream;
            outputStream.write("HTTP/1.1 500 ERROR\r\n".getBytes("UTF-8"));
            outputStream.write("Content-Type: application/json\r\n".getBytes("UTF-8"));
            outputStream.write(("Content-Length: " + responseBytes.length + "\r\n").getBytes("UTF-8"));
            outputStream.write("\r\n".getBytes("UTF-8"));
            outputStream.write(responseBytes);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void close() throws IOException {
        this.outputStream.close();
    }



}
